<script setup>
import {onMounted, ref} from "vue";
import {ImageFeatureDB} from '@/api/db/indexDb.js'
import {ImageAlgorithms} from '@/utils/algorithm.js'
import {ClipboardManager} from '@/utils/clipboard.js'
import {BatchProcessor} from '@/utils/batchProcessor.js'

const pastedImages = {
  library: ref(null),
  search: ref(null)
};
// 添加新的响应式变量来存储待处理的文件
const pendingFiles = ref([]);
const clipboardManager = ref(null)
const db = ref(null);
const performanceStats = {
  totalImagesProcessed: ref(0),
  averageProcessingTime: ref(0)
};

// 通过ID获取元素并修改样式
const getElement = (id) => document.getElementById(id);

const initialize = () => {
  clipboardManager.value = new ClipboardManager();
  clipboardManager.value.init();
  // 注册剪贴板粘贴区域
  clipboardManager.value.registerPasteArea('libraryPasteArea', (blob) => {
    handleLibraryPaste(blob);
  });

  db.value = new ImageFeatureDB();
  db.value.init();

};

const handleLibraryPaste = async (blob) => {
  try {
    updateStatus('正在处理粘贴的图片...');

    // 创建预览
    const previewUrl = URL.createObjectURL(blob);
    getElement('libraryPastePreview').innerHTML = `<img src="${previewUrl}" class="paste-preview" alt="预览">`;
    const libraryFilename = getElement('libraryFilename');
    libraryFilename.value = clipboardManager.value.generateDefaultFilename();
    // 存储图片数据
    pastedImages.library.value = {
      blob: blob,
      previewUrl: previewUrl
    };

    updateStatus('图片已粘贴到图库，可以修改名称后点击"处理并入库"');

  } catch (error) {
    updateStatus('粘贴图片处理失败: ' + error.message, true);
  }
};



const handleFileSelect = async (event) => {
  let files = [];

  // 使用传统文件选择
  files = Array.from(event.target.files);

  if (!files.length) {
    updateStatus('请先选择图片文件或粘贴图片', true);
    return;
  }

  // 将文件存储到待处理列表
  pendingFiles.value = files;

  // 更新状态提示用户点击处理按钮
  updateStatus(`已选择 ${files.length} 个文件，点击"处理并入库"按钮开始处理`, false);

  // 清空文件输入框
  const imageUpload = getElement('imageUpload');
  imageUpload.value = '';

};

// 新增处理并入库函数
const processAndStoreImages = async () => {
  let files = [];
  // 检查是否有粘贴的图片
  if (pastedImages.library.value) {
    // 创建伪File对象
    const libraryFilename = getElement('libraryFilename');
    const filename = libraryFilename.value || clipboardManager.value.generateDefaultFilename();
    const file = new File([pastedImages.library.value.blob], filename, {
      type: pastedImages.library.value.blob.type
    });
    files = [file];
    pendingFiles.value = files;

    // 清理粘贴数据
    URL.revokeObjectURL(pastedImages.library.value.previewUrl);
    getElement('libraryPastePreview').innerHTML = '';
    libraryFilename.value = '';
    pastedImages.library.value = null;
  }

  if (!pendingFiles.value.length) {
    updateStatus('没有待处理的文件', true);
    return;
  }

  const processBtn = getElement('processBtn');
  const progress = getElement('progress');

  processBtn.disabled = true;
  progress.style.display = 'block';
  progress.value = 0;

  const batchProcessor = new BatchProcessor(3); // 同时处理3张图片
  const tasks = pendingFiles.value.map((file, index) =>
      () => processSingleImage(file, index, pendingFiles.value.length)
  );

  try {
    const results = await batchProcessor.process(tasks);
    const successCount = results.filter(r => r.success).length;
    const errorCount = results.filter(r => !r.success).length;

    processBtn.disabled = false;
    progress.style.display = 'none';

    let statusMessage = `处理完成！成功: ${successCount}`;
    if (errorCount > 0) {
      statusMessage += `, 失败: ${errorCount}`;
    }

    updateStatus(statusMessage, errorCount > 0);

    // 清空待处理文件列表
    pendingFiles.value = [];

  } catch (error) {
    updateStatus('处理图片时出错：' + error.message, true);
    processBtn.disabled = false;
    progress.style.display = 'none';
  }
};

const processSingleImage = async (file, index, total) => {
  const startTime = performance.now();
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = async () => {
      try {
        const algorithms = new ImageAlgorithms();
        // 并行计算所有特征
        const [thumbnail, colorHistogram, perceptualHash, colorHash] = await Promise.all([
          algorithms.createThumbnail(img),
          algorithms.calculateColorHistogram(img),
          algorithms.calculatePerceptualHash(img),
          algorithms.calculateColorHash(img)
        ]);

        const features = {
          colorHistogram,
          perceptualHash,
          colorHash
        };

        await db.value.storeImageFeatures(file.name, features, thumbnail);

        URL.revokeObjectURL(img.src);
        console.log('已处理图片:', db.value.getImageCount())
        // 更新进度和性能统计
        const progress = getElement('progress');
        progress.value = ((index + 1) / total) * 100;
        updateStatus(`处理中: ${file.name} (${index + 1}/${total})`);

        const processingTime = performance.now() - startTime;
        updatePerformanceStats(processingTime);

        resolve();
      } catch (error) {
        reject(error);
      }
    };

    img.onerror = () => reject(new Error('图片加载失败: ' + file.name));
    img.src = URL.createObjectURL(file);
  });
};

const updatePerformanceStats = (processingTime) => {
  // 统计处理时间
  performanceStats.totalImagesProcessed.value++;
  performanceStats.averageProcessingTime.value =
      (performanceStats.averageProcessingTime.value * (performanceStats.totalImagesProcessed.value - 1) + processingTime)
      / performanceStats.totalImagesProcessed.value;
};

const clearLibrary = async () => {
  if (!confirm('确定要清空整个图片库吗？此操作不可恢复。')) {
    return;
  }

  try {
    await db.value.clearDatabase();
    updateStatus('图片库已清空');
    await updateLibraryInfo();
    getElement('results').innerHTML = '';
  } catch (error) {
    updateStatus('清空失败: ' + error.message, true);
  }
};

const updateLibraryInfo = async () => {
  const count = await db.value.getImageCount();
  getElement('status').innerHTML = `📊 图片库: <strong>${count}</strong> 张图片`;
};

const updateStatus = (message, isError = false) => {
  const status = getElement('status');
  status.textContent = message;
  status.style.color = isError ? '#ea4335' : '#333';
  console.log('Status:', message);
};

onMounted(() => {
  initialize();
})
</script>

<template>
  <div class="section">
    <h3>📁 构建图片库</h3>

    <!-- 文件上传方式 -->
    <div class="upload-options">
      <label class="upload-option-btn">
        <div>📎 选择文件</div>
        <input type="file" id="imageUpload" multiple accept="image/*" class="hidden" @change="handleFileSelect">
      </label>
      <div class="upload-option-btn" id="pasteToLibraryBtn">
        <div>📋 粘贴图片</div>
      </div>
    </div>

    <!-- 粘贴区域 -->
    <div class="upload-area" id="libraryPasteArea">
      <div class="upload-icon">📋</div>
      <p><strong>粘贴截图到此处</strong></p>
      <p>点击此区域后按 Ctrl+V 粘贴要添加到图库的截图</p>
      <div id="libraryPastePreview"></div>
      <input type="text" id="libraryFilename" class="filename-input" placeholder="输入图片名称（可选）" value="">
    </div>

    <button id="processBtn" @click="processAndStoreImages">处理并入库</button>
    <button id="clearBtn" class="clear-btn" @click="clearLibrary">清空图库</button>
    <progress id="progress" value="0" max="100" style="display: none;"></progress>
    <div id="status">准备就绪</div>
  </div>
</template>

<style scoped>

.section {
  margin-bottom: 15px;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 5px;
  background: #fafafa;
}
h3 {
  margin-top: 0;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 5px;
}
button {
  margin: 5px;
  padding: 8px 12px;
  background: #4285f4;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  font-size: 12px;
}
button:hover { background: #3367d6; }
button:disabled { background: #ccc; cursor: not-allowed; }
select, input {
  padding: 6px;
  border: 1px solid #ddd;
  border-radius: 3px;
  font-size: 12px;
}
#status, #results {
  margin-top: 10px;
  padding: 10px;
  background: white;
  border-radius: 3px;
  min-height: 20px;
  border: 1px solid #e0e0e0;
}

progress { width: 100%; }
.config-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 8px 0;
}

.clear-btn {
  background: #ea4335;
}
.clear-btn:hover {
  background: #d33426;
}
.upload-area {
  border: 2px dashed #ccc;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  margin: 10px 0;
  background: white;
  cursor: pointer;
  transition: all 0.3s;
}
.upload-area:hover, .upload-area.dragover {
  border-color: #4285f4;
  background: #f0f7ff;
}
.upload-area p {
  margin: 5px 0;
  color: #666;
}
.upload-area.active {
  border-color: #4285f4;
  background: #f0f7ff;
  box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.2);
}

.upload-area:focus {
  border-color: #4285f4;
  background: #f0f7ff;
  outline: none;
}
.upload-icon {
  font-size: 24px;
  margin-bottom: 8px;
  color: #4285f4;
}
.upload-options {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}
.upload-option-btn {
  flex: 1;
  padding: 8px;
  background: #f8f9fa;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}
.upload-option-btn:hover {
  background: #e8f0fe;
  border-color: #4285f4;
}
.filename-input {
  width: 100%;
  margin-top: 8px;
  padding: 6px;
  border: 1px solid #ddd;
  border-radius: 3px;
}

.hidden {
  display: none;
}
</style>